import { defineStore } from 'pinia'

import { info, login, logout, register, updateInfo, updatePassword } from './api'

import { InfoDTO, Login, PwdDTO, UserState } from './data.d'

import cache from '@/utils/cache'
import { Role } from '@/utils/enum'

export const useUserStore = defineStore('userStore', {
  state: (): UserState => ({
    // 用户信息
    user: {
      id: null,
      role: Role.USER,
      username: '',
      nickname: '',
      status: '',
      avatarUrl: null,
    },
    token: cache.getToken(),
  }),
  actions: {
    // 账号密码登录
    async accountLoginAction(data: Omit<Login, 'nickname'>, isStr: boolean = true) {
      const res = await login(data, isStr)
      if (res.code === 0) {
        const { token, id, username, nickname, role, status, avatarUrl } = res.data
        cache.setToken(token!)
        this.token = token
        Object.assign(this.user, { id, username, nickname, role, status, avatarUrl })
      }
      return res.code === 0
    },
    // 获取用户信息
    async getUserInfoAction() {
      const res = await info()

      const { id, username, nickname, role, status, avatarUrl } = res.data
      Object.assign(this.user, { id, username, nickname, role, status, avatarUrl })
    },
    // 用户退出
    async logoutAction() {
      await logout()

      cache.removeToken()
      this.user.id = ''
      this.user.role = Role.USER
      this.token = null
    },
    // 注册
    async registerAction(data: Login) {
      const res = await register(data)
      if (res.code === 0) {
        const { username, password } = data
        return this.accountLoginAction({ username, password }, false)
      } else {
        return false
      }
    },
    // 更新信息
    async updateInfoAction(data: InfoDTO) {
      const res = await updateInfo(data)
      return res.code === 0
    },
    // 更新密码
    async updatePwdAction(data: PwdDTO) {
      const res = await updatePassword(data)
      return res.code === 0
    },
  },
})
